from PyQt4 import QtGui, QtCore
from osdep.osdep_code import get_osdep_mixin

import logging
logger = logging.getLogger(__name__)

from view.gen import mainwindow
from view.widgets import TextDialog

class MainWindow(get_osdep_mixin(), QtGui.QMainWindow):
	def __init__(self, model, clipboard, parent=None):
		"""	model: model from where we get tokens and different available parsers
			clipboard: used to self clipboard data
			paste_function: function that is used to send ctrl-v to PS. There are two versions
				available depending on the used shortcut, i.e. the simple one when the shortcut
				is ctrl-<something> (only send a single 'V') and the complex one that handles everything
				If send_paste module can't be loaded we use a function that does nothing
		"""
		super().__init__(parent)
		self._model = model
		self._clipboard = clipboard
		self._ui = mainwindow.Ui_MainWindow()
		self._ui.setupUi(self)
		self._ui.btn_next.clicked.connect(self.next_token)
		self._ui.btn_prev.clicked.connect(self.prev_token)
		self._ui.actionClose.triggered.connect(self.close)
		self._ui.actionNew_Text.triggered.connect(self.on_new_text)
		self._ui.te_text.setReadOnly(True)
		# set flags so that we have a visible cursor
		self._ui.te_text.setTextInteractionFlags(QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
		self._ui.te_text.setStyleSheet("selection-background-color: yellow; selection-color: black")
		self._ui.te_text.installEventFilter(self)
		# we want to show the "select text" dialog not only when selecting it via file menu,
		# but also when the user first clicks onto the textedit
		self._startup = True
		self._ui.le_line.setReadOnly(True)

	def eventFilter(self, obj, event):
		if self._startup and event.type() == QtCore.QEvent.FocusIn and obj == self._ui.te_text:
			# at startup when clicking into the text edit field we want to show the dialog
			self._startup = False
			self.on_new_text()
		return super().eventFilter(obj, event)
	
	def next_token(self):
		token = self._model.next_token()
		if token:
			self._update_gui(token)
		
	def prev_token(self):
		token = self._model.prev_token()
		if token:
			self._update_gui(token)
	
	def on_new_text(self):
		"""Called either when clicking on File->New Text or when at startup clicking into the major textfield
		Show textdialog and then update text and create new parser afterwards."""
		dialog = TextDialog(self._model.parser_names(), self)
		res = dialog.exec_()
		if res:	# user clicked ok
			parser_name, text = res
			self._model.set_parser(parser_name, text)
			textedit = self._ui.te_text
			textedit.clear()
			textedit.insertPlainText(text)
			self._ui.lbl_page.setText("")
			self._ui.lbl_panel.setText("")
			self._ui.le_line.setText("")
			
	def _update_gui(self, token):
		""" Updates labels, taskbar, copies text into clipboard and if
	 		possible sends ctrl-v to application."""
		self._ui.lbl_page.setText(token.page)
		self._ui.lbl_panel.setText(token.panel)
		self._ui.le_line.setText(token.text)
		self._center_cursor(token)
		self._update_taskbar(token)
		self._set_clipboard_text(token.text)
		self._paste_text()
	
	def _set_clipboard_text(self, text):
		self._clipboard.setText(text)
	
	def _center_cursor(self, token):
		""" Center cursor around current line of given token
		and select it."""
		textedit = self._ui.te_text
		# remove line wrapping, so that blockNumber corresponds directly to a real linenumber, 
		# afterwards add line wrapping again.
		textedit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
		old_line = textedit.textCursor().blockNumber()
		line = token.line
		diff = line - old_line
		move = QtGui.QTextCursor.Down if diff >= 0 else QtGui.QTextCursor.Up
		for _ in range(abs(diff)): textedit.moveCursor(move, QtGui.QTextCursor.MoveAnchor)
		# select current line
		textedit.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.MoveAnchor)
		textedit.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
		textedit.setLineWrapMode(QtGui.QPlainTextEdit.WidgetWidth)
		# make sure that line is centered on screen - this has to be done after line wrapping
		# is activated
		textedit.centerCursor()

	def closeEvent(self, event):
		self.unregister_hotkey()
		event.accept()

	def _update_taskbar(self, token):
		text = "TSH - pg{0.page}/{0.panel}".format(token)
		self.set_taskbar_text(text)
